package gitobject;

import repository.Repository;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class Index implements Serializable {

    public HashMap<String, GitObject> fileOb = new HashMap<>();    //保存file信息.time和blob
    public Index() {

    }



    static public String getTime(File file){
        Long lastModified = file.lastModified();
        Date date = new Date(lastModified);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(date);
        return time;
    }



    public void addFile(File file) throws Exception{
        if (file.isFile()) {
            Blob blob = new Blob(file);
            String time = getTime(file);
            if(!fileOb.containsValue(time)) {
                fileOb.put(time, blob);
            }
            return;

        }
        if (file.isDirectory()) {
            Tree tree = new Tree(file);
            String time = getTime(file);
            if(!fileOb.containsValue(time)) {
                fileOb.put(time, tree);
            }
            return;
        }
    }


    public void writeObject() throws Exception {
        //写序列
        File file = new File(Repository.getGitDir() + File.separator + "index");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(this);
        objectOutputStream.close();
    }


    public static Index deserialize(File file) throws IOException, ClassNotFoundException {
        //对文件对象进行反序列
        FileInputStream fileInputStream = new FileInputStream(file);
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        Index index = (Index) objectInputStream.readObject();
        objectInputStream.close();
        return index;
    }
}
